package com.finger.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.finger.eduservice.entity.EduSubject;
import com.finger.eduservice.entity.excel.ExcelSubjectData;
import com.finger.eduservice.entity.subject.OneSubject;
import com.finger.eduservice.entity.subject.TwoSubject;
import com.finger.eduservice.listener.ExcelSubjectListener;
import com.finger.eduservice.mapper.EduSubjectMapper;
import com.finger.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-01-03
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void importSubjectData(MultipartFile file, EduSubjectService eduSubjectService) {
        try {
            InputStream is = file.getInputStream();
            EasyExcel.read(is, ExcelSubjectData.class,new ExcelSubjectListener(eduSubjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getSubjectTree() {

        List<OneSubject> finalSubjectTree = new ArrayList<>();

        QueryWrapper<EduSubject> oneWrapper = new QueryWrapper();

        oneWrapper.eq("parent_id","0");

        // 获取一级分类的集合
        List<EduSubject> oneSubjects = baseMapper.selectList(oneWrapper);

        QueryWrapper<EduSubject> twoWrapper = new QueryWrapper<>();

        twoWrapper.ne("parent_id","0");

        //获取二级分类的集合
        List<EduSubject> twoSubjects = baseMapper.selectList(twoWrapper);


        for (EduSubject oneEduSubject : oneSubjects) {
            OneSubject oneSubject = new OneSubject();

            BeanUtils.copyProperties(oneEduSubject,oneSubject);

            for (EduSubject twoEduSubject : twoSubjects) {

                if(Objects.equals(oneEduSubject.getId(),twoEduSubject.getParentId())){

                    TwoSubject twoSubject = new TwoSubject();

                    BeanUtils.copyProperties(twoEduSubject,twoSubject);

                    oneSubject.getChildren().add(twoSubject);
                }
            }

            finalSubjectTree.add(oneSubject);

        }

        return finalSubjectTree;
    }
}
